import { Context } from 'koa'
import articleService from '../services/article'

export class ArticleController {
  // 创建文章
  async create(ctx: Context) {
    const articleData = ctx.request.body
    const article = await articleService.create(articleData)
    ctx.status = 201
    ctx.body = {
      success: true,
      data: article,
      message: '文章创建成功'
    }
  }

  // 更新文章
  async update(ctx: Context) {
    const { id } = ctx.params
    const updateData = ctx.request.body
    const article = await articleService.update(parseInt(id), updateData)
    ctx.status = 200
    ctx.body = {
      success: true,
      data: article,
      message: '文章更新成功'
    }
  }

  // 删除文章
  async delete(ctx: Context) {
    const { id } = ctx.params
    await articleService.delete(parseInt(id))
    ctx.status = 200
    ctx.body = {
      success: true,
      message: '文章删除成功'
    }
  }

  // 查询单个文章
  async findOne(ctx: Context) {
    const { id } = ctx.params
    const article = await articleService.findOne(parseInt(id))
    ctx.status = 200
    ctx.body = {
      success: true,
      data: article,
      message: '查询成功'
    }
  }

  // 查询所有文章
  async findAll(ctx: Context) {
    const articles = await articleService.findAll(ctx.query)
    ctx.status = 200
    ctx.body = {
      success: true,
      data: articles,
      message: '查询成功'
    }
  }

  // 增加文章浏览量
  async increaseViewCount(ctx: Context) {
    const { id } = ctx.params
    const article = await articleService.increaseViewCount(parseInt(id))
    ctx.status = 200
    ctx.body = {
      success: true,
      data: article,
      message: '浏览量更新成功'
    }
  }
}

export const articleController = new ArticleController()
